package com.cnblogs.leizia.crm.workbench.web.controller;

import com.cnblogs.leizia.crm.commen.ErrorCode;
import com.cnblogs.leizia.crm.commen.RequestUri;
import com.cnblogs.leizia.crm.commen.Result;
import com.cnblogs.leizia.crm.exception.ActivityException;
import com.cnblogs.leizia.crm.settings.domain.User;
import com.cnblogs.leizia.crm.settings.service.UserService;
import com.cnblogs.leizia.crm.settings.service.impl.UserServiceImpl;
import com.cnblogs.leizia.crm.utils.DateTimeUtil;
import com.cnblogs.leizia.crm.utils.PrintJson;
import com.cnblogs.leizia.crm.utils.ServiceFactory;
import com.cnblogs.leizia.crm.utils.UUIDUtil;
import com.cnblogs.leizia.crm.vo.PaginationVo;
import com.cnblogs.leizia.crm.workbench.domain.Activity;
import com.cnblogs.leizia.crm.workbench.service.ActivityService;
import com.cnblogs.leizia.crm.workbench.service.impl.ActivityServiceImpl;
import com.github.pagehelper.PageHelper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author leizi
 * @create 2021-02-16 12:45
 */
public class ActivityController extends HttpServlet {

    private ActivityService activityService = (ActivityService) ServiceFactory.getService(new ActivityServiceImpl());
    private UserService userService = (UserService) ServiceFactory.getService(new UserServiceImpl());

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getServletPath();
        // 获取用户信息列表
        if (RequestUri.ACTIVITY_GET_USER_LIST.getUriPath().equals(path)) {
            List<User> userList = userService.getUserList();
            PrintJson.printJsonObj(resp, Result.successToDataResult(userList));
        }
        // 保存市场活动信息
        if (RequestUri.ACTIVITY_SAVE.getUriPath().equals(path)) {
            activitySave(req, resp);
        }
        // 分页获取记录
        if (RequestUri.ACTIVITY_PAGE_LIST.getUriPath().equals(path)) {
            activityPageList(req, resp);
        }
        // 删除市场活动记录
        if (RequestUri.ACTIVITY_DELETE.getUriPath().equals(path)) {
            activityDelete(req, resp);
        }
        // 编辑市场活动
        if (RequestUri.ACTIVITY_EDIT.getUriPath().equals(path)) {
            editActivity(req, resp);
        }
        // 更新市场活动
        if (RequestUri.ACTIVITY_UPDATE.getUriPath().equals(path)) {
            updateActivity(req, resp);
        }
        // 转发到详情页
        if (RequestUri.ACTIVITY_FORWARD_DETAIL.getUriPath().equals(path)) {
            forwardDetail(req, resp);
        }
    }

    /**
     * 跳转到详情页
     *
     * @param request
     * @param response
     * @return
     */
    private Result forwardDetail(HttpServletRequest request, HttpServletResponse response) {
        // 根据市场活动id获取信息回显
        String id = request.getParameter("id");
        try {
            Activity activity = activityService.getDetail(id);

            // 详情信息保存到request域中
            request.setAttribute("activity", activity);
            // 转发到详情页
            request.getRequestDispatcher("/workbench/activity/detail.jsp").forward(request, response);
        } catch (ActivityException e) {
            e.printStackTrace();
            PrintJson.printJsonObj(response, Result.errorResult(e.getMessage()));
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 更新市场活动
     *
     * @param request
     * @param response
     * @return
     */
    private Result updateActivity(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        String owner = request.getParameter("owner");
        String name = request.getParameter("name");
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        String cost = request.getParameter("cost");
        String description = request.getParameter("description");
        Activity activity = new Activity();
        activity.setId(id);
        activity.setOwner(owner);
        activity.setName(name);
        activity.setStartDate(startDate);
        activity.setEndDate(endDate);
        activity.setCost(cost);
        activity.setDescription(description);
        // 获取session域中当前登录用户信息
        User user = (User) request.getSession().getAttribute("user");
        // 设置修改人
        activity.setEditBy(user.getName());
        // 设置修改时间
        activity.setEditTime(DateTimeUtil.getSysTime());

        try {
            // 更新市场活动记录信息
            activityService.updateActivity(activity);
            PrintJson.printJsonObj(response, Result.successResult());
        } catch (Exception e) {
            e.printStackTrace();
            PrintJson.printJsonObj(response, Result.errorResult(e.getMessage()));
        }

        return null;
    }

    /**
     * 编辑市场活动
     *
     * @param request
     * @param response
     * @return
     */
    private Result editActivity(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");

        try {
            // 根据id获取市场活动记录信息
            Activity activity = activityService.editActivity(id);
            // 获取用户列表
            List<User> userList = userService.getUserList();

            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("userList", userList);
            resultMap.put("activityInfo", activity);
            PrintJson.printJsonObj(response, Result.successToDataResult(resultMap));
        } catch (Exception e) {
            e.printStackTrace();
            PrintJson.printJsonObj(response, Result.errorResult(e.getMessage()));
        }

        return null;
    }

    /**
     * 保存市场活动
     *
     * @param request
     * @param response
     */
    private void activitySave(HttpServletRequest request, HttpServletResponse response) {
        // 解析参数
        String owner = request.getParameter("owner");
        String name = request.getParameter("name");
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        String cost = request.getParameter("cost");
        String description = request.getParameter("description");
        Activity activity = new Activity();
        activity.setId(UUIDUtil.getUUID());
        activity.setOwner(owner);
        activity.setName(name);
        activity.setStartDate(startDate);
        activity.setEndDate(endDate);
        activity.setCost(cost);
        activity.setDescription(description);
        activity.setCreateTime(DateTimeUtil.getSysTime());
        User user = (User) request.getSession().getAttribute("user");
        activity.setCreateBy(user.getName());

        boolean flag = activityService.activitySave(activity);
        if (flag) {
            PrintJson.printJsonObj(response, Result.successResult());
        } else {
            PrintJson.printJsonObj(response, Result.errorResult(ErrorCode.ACTIVITY_ERROR.getMsg()));
        }
    }

    /**
     * 市场活动分页查询列表
     *
     * @param request
     * @param response
     * @return
     */
    private Result activityPageList(HttpServletRequest request, HttpServletResponse response) {
        String pageNo = request.getParameter("pageNo");
        String pageSize = request.getParameter("pageSize");
        String owner = request.getParameter("owner");
        String name = request.getParameter("name");
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        PageHelper.startPage(Integer.valueOf(pageNo), Integer.valueOf(pageSize));
        Map<String, Object> activityPageMap = new HashMap<>();
        activityPageMap.put("owner", owner);
        activityPageMap.put("name", name);
        activityPageMap.put("startTime", startDate);
        activityPageMap.put("endTime", endDate);

        // 获取市场活动列表
        PaginationVo<Activity> pageList = activityService.activityPageList(activityPageMap);

        PrintJson.printJsonObj(response, Result.successToDataResult(pageList));

        return null;
    }


    /**
     * 根据ids删除市场活动记录
     * (市场活动表与市场活动备注表关联删除记录)
     *
     * @return
     */
    private Result activityDelete(HttpServletRequest request, HttpServletResponse response) {
        String[] ids = request.getParameterValues("id");
        boolean result = activityService.activityDelete(ids);

        if (result) {
            // 删除成功
            PrintJson.printJsonObj(response, Result.successResult());
        } else {
            // 删除失败
            PrintJson.printJsonObj(response, Result.errorResult(ErrorCode.ACTIVITY_DELETE_ERROR.getMsg()));
        }

        return null;
    }
}
